package com.yunchao.library.socket.model.security

import com.yunchao.library.socket.extensions.toReadOnlyBuffer


data class AutographData(
    val id: UInt,          // U4类型，最高位必须为0
    val fragment: UInt,    // U4类型，控制数据时为0
    val flags: UByte,      // U1类型，第8位标识使用提交/控制数据
    val algorithm: UByte,  // U1类型，当前0x01表示SHA-1
    val length: UShort,    // U2类型，当前20
    val value: ByteArray   // U1[length]，实际内容
) {
    /**
     * 判断是否使用提交数据
     */
    fun isSubmitData(): Boolean = (flags and 0x80u) != 0u.toUByte()

    /**
     * 验证ID最高位是否为0
     */
    fun validateId(): Boolean = (id and 0x80000000u) == 0u

    companion object {

        fun fromByteArray(bytes: ByteArray): AutographData {
            val buffer = bytes.toReadOnlyBuffer()
            // 解析各字段
            val id = buffer.int.toUInt() and 0x7FFFFFFFu
            val fragment = buffer.int.toUInt()
            val flags = buffer.get().toUByte()
            val algorithm = buffer.get().toUByte()
            val length = buffer.short.toUShort()
            // 读取value
            val value = ByteArray(length.toInt()).also {
                buffer.get(it)
                require(buffer.position() <= buffer.limit()) { "数据长度不足" }
            }

            return AutographData(
                id = id,
                fragment = fragment,
                flags = flags,
                algorithm = algorithm,
                length = length,
                value = value
            )
        }

    }
}
